package com.industrial.premu.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.Page;
import com.industrial.common.core.domain.R;
import com.industrial.common.core.exception.ServiceException;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.utils.MD5Utils;
import com.industrial.common.core.utils.poi.ExcelUtil;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.DictUtils;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.premu.domain.*;
import com.industrial.premu.domain.sqsj.PreMuImportBenefitEvaluationNo;
import com.industrial.premu.dto.PreMuCompanyInfoThirdDto;
import com.industrial.premu.mapper.*;
import com.industrial.premu.util.ValidationUtil;
import com.industrial.premu.vo.ProcessCompanyInfoVo;
import com.industrial.system.api.RemoteUserService;
import com.industrial.system.api.domain.SysRole;
import com.industrial.system.api.domain.SysUser;
import com.industrial.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import com.industrial.premu.service.IPreMuCompanyInfoService;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.validation.ValidationException;

/**
 * 企业基本信息Service业务层处理
 *
 * @author SangGuangCan
 * @date 2024-01-24
 */
@Service
public class PreMuCompanyInfoServiceImpl implements IPreMuCompanyInfoService
{
    @Autowired
    private PreMuCompanyInfoMapper preMuCompanyInfoMapper;

    @Autowired
    private SysOperErrorMapper sysOperErrorMapper;


    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private PreMuCompanyInfoNoMapper preMuCompanyInfoNoMapper;

    @Autowired
    private PreMuBenefitEvaluationNoMapper preMuBenefitEvaluationNoMapper;

    @Autowired
    private PreMuBenefitEvaluationMapper preMuBenefitEvaluationMapper;

    private Integer BACTH_COUNT = 100;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private PreMuIndexWeightMainMapper preMuIndexWeightMainMapper;

    @Autowired
    private ValidationUtil validationUtil;

    @Value("${file.pre}")
    private String filePre;

    @Autowired
    private PlatformTransactionManager transactionManager;

    private static final int BATCH_SIZE = 200;

    /**
     * 查询企业基本信息
     *
     * @param preMuCompanyInfo 企业基本信息主键
     * @return 企业基本信息
     */
    @Override
    public AjaxResult selectPreMuCompanyInfoById(PreMuCompanyInfo preMuCompanyInfo)
    {
        if(StringUtils.isBlank(preMuCompanyInfo.getNum())){
            return AjaxResult.warn("请确定要编辑的是规上还是规下");
        }
        //参评企业
        if(StringUtils.equals(preMuCompanyInfo.getNum(),"1")){
            PreMuCompanyInfo preMuCompanyInfo1 = preMuCompanyInfoMapper.selectPreMuCompanyInfoById(preMuCompanyInfo.getId());
            return AjaxResult.success(preMuCompanyInfo1);
        }else if(StringUtils.equals(preMuCompanyInfo.getNum(),"2")){
            //不参评企业
            PreMuCompanyInfoNo preMuCompanyInfoNo = preMuCompanyInfoNoMapper.selectPreMuCompanyInfoNoById(preMuCompanyInfo.getId());
            return AjaxResult.success(preMuCompanyInfoNo);
        }

        return AjaxResult.warn("没有找到类型");
    }

    /**
     * 查询企业基本信息列表
     *
     * @param preMuCompanyInfo 企业基本信息
     * @return 企业基本信息
     */
    @Override
    public List<PreMuCompanyInfo> selectPreMuCompanyInfoList(PreMuCompanyInfo preMuCompanyInfo)
    {
        if(StringUtils.isBlank(preMuCompanyInfo.getNum())){
            throw new RuntimeException("请选择是否参评");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Set<String> roles = loginUser.getRoles();
        SysUser sysUser = loginUser.getSysUser();

        if(ArrayUtil.containsAny(roles.toArray(),"x_01_011","along_yellow_river")){
            preMuCompanyInfo.setCounty(sysUser.getDistrict());
        }else if(ArrayUtil.contains(roles.toArray(),"s_01_011")){
            preMuCompanyInfo.setCity(sysUser.getCity());
        }else if(ArrayUtil.contains(roles.toArray(),"p_01_011")){
            preMuCompanyInfo.setProvince(sysUser.getProvince());
        }else if(ArrayUtil.contains(roles.toArray(),"q_01_001")){
            String uscc = SecurityUtils.getLoginUser().getUsername();
//            PreMuCompanyInfo enterPreMuCompanyInfo = new PreMuCompanyInfo();
            preMuCompanyInfo.setUscc(uscc);
//            enterPreMuCompanyInfo.setCompanyType(preMuCompanyInfo.getCompanyType());
//            return preMuCompanyInfoMapper.selectPreMuCompanyInfoList(enterPreMuCompanyInfo);
        }

        if(StringUtils.isNotBlank(preMuCompanyInfo.getModuleType())){
            preMuCompanyInfo.setModuleType(getModuleType(preMuCompanyInfo.getModuleType()));
        }


        if(StringUtils.equals(preMuCompanyInfo.getNum(),"1")){
            return preMuCompanyInfoMapper.selectPreMuCompanyInfoList(preMuCompanyInfo);
        }else if(StringUtils.equals(preMuCompanyInfo.getNum(),"2")){
            PreMuCompanyInfoNo preMuCompanyInfoNo = new PreMuCompanyInfoNo();
            BeanUtil.copyProperties(preMuCompanyInfo,preMuCompanyInfoNo);
            List<PreMuCompanyInfoNo> preMuCompanyInfoNos = preMuCompanyInfoNoMapper.selectPreMuCompanyInfoNoList(preMuCompanyInfoNo);
//            List<PreMuCompanyInfo> result = new ArrayList<>();
//            for(PreMuCompanyInfoNo item : preMuCompanyInfoNos){
//                PreMuCompanyInfo temp = new PreMuCompanyInfo();
//                BeanUtil.copyProperties(item,temp);
//                result.add(temp);
//            }
            //通过代码处理数据分页
            if(preMuCompanyInfoNos instanceof Page){
                Page page = (Page) preMuCompanyInfoNos;
                int pageNum = page.getPageNum();
                int pageSize = page.getPageSize();
                long total = page.getTotal();
                com.github.pagehelper.Page<PreMuCompanyInfo>  pp =new Page<>();
                for(PreMuCompanyInfoNo item : preMuCompanyInfoNos){
                    PreMuCompanyInfo temp = new PreMuCompanyInfo();
                    BeanUtil.copyProperties(item,temp);
                    pp.add(temp);
                }
                pp.setTotal(total);
                pp.setPageNum(pageNum);
                pp.setPageSize(pageSize);
                return pp;
            }
        }
        throw new RuntimeException("没有找到指定的类型");
    }

    /**
     * 新增企业基本信息
     *
     * @param preMuCompanyInfo 企业基本信息
     * @return 结果
     */
    @Override
    public int insertPreMuCompanyInfo(PreMuCompanyInfo preMuCompanyInfo)
    {

        return preMuCompanyInfoMapper.insertPreMuCompanyInfo(preMuCompanyInfo);
    }

    /**
     * 修改企业基本信息
     *
     * @param preMuCompanyInfo 企业基本信息
     * @return 结果
     */
    @Override
    public int updatePreMuCompanyInfo(PreMuCompanyInfo preMuCompanyInfo)
    {
        PreMuBenefitEvaluation params = new PreMuBenefitEvaluation();
        params.setCompanyId(preMuCompanyInfo.getId());
        List<PreMuBenefitEvaluation> preMuBenefitEvaluations = preMuBenefitEvaluationMapper.selectPreMuBenefitEvaluationListOrStatus(params);
        if(preMuBenefitEvaluations != null && preMuBenefitEvaluations.size() > 1){
            throw new RuntimeException("确认企业信息失败。");
        }
        if(preMuBenefitEvaluations != null && !preMuBenefitEvaluations.isEmpty()){
            PreMuBenefitEvaluation preMuBenefitEvaluation = preMuBenefitEvaluations.get(0);
            String status = preMuBenefitEvaluation.getStatus();
            if(StringUtils.isNotBlank(status)){
                Integer statusInt = Integer.valueOf(status);
                if(statusInt >= 1){
                    throw new RuntimeException("该企业亩产数据已核实不可以修改");
                }
            }
        }

        //如果Logo不为空，去掉http的前缀
        if(StringUtils.isNotBlank(preMuCompanyInfo.getLogo())){
            preMuCompanyInfo.setLogo( "/file" + StrUtil.removePrefix(preMuCompanyInfo.getLogo(),filePre));
        }

        return preMuCompanyInfoMapper.updatePreMuCompanyInfo(preMuCompanyInfo);
    }

    /**
     * 批量删除企业基本信息
     *
     * @param ids 需要删除的企业基本信息主键
     * @return 结果
     */
    @Override
    public int deletePreMuCompanyInfoByIds(String[] ids)
    {
        return preMuCompanyInfoMapper.deletePreMuCompanyInfoByIds(ids);
    }

    /**
     * 删除企业基本信息信息
     *
     * @param id 企业基本信息主键
     * @return 结果
     */
    @Override
    public int deletePreMuCompanyInfoById(String id)
    {
        return preMuCompanyInfoMapper.deletePreMuCompanyInfoById(id);
    }

    /**
     * 导入企业数据
     *
     * @param file
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult importEnterInfo(Map<String,String> prams,MultipartFile file) {
        if(file.isEmpty()){
            return AjaxResult.warn("没有找到需要导入的企业文件");
        }
        //模块类型
        String moduleType = prams.get("moduleType");
        //企业类型
        String companyType = prams.get("companyType");
        //判断是否是参评企业
        String num = prams.get("num");

        if(StringUtils.isBlank(moduleType) || StringUtils.isBlank(moduleType)){
            return AjaxResult.warn("请选择模块或者企业类型");
        }

        try {
            ExcelUtil<PreMuCompanyInfo> util = new ExcelUtil<PreMuCompanyInfo>(PreMuCompanyInfo.class);
            List<PreMuCompanyInfo> preMuCompanyInfos = util.importExcel(file.getInputStream());
            //System.out.println("导入新增企业信息:"+ JSON.toJSONString(preMuCompanyInfos));

            if(preMuCompanyInfos == null || preMuCompanyInfos.isEmpty()){
                return AjaxResult.warn("没有加载到Excel中的数据");
            }
            //获取当前年份
            int year = DateUtil.year(DateUtils.getNowDate()) - 1;

            SysUser sysUserInfo = SecurityUtils.getLoginUser().getSysUser();
            if (Objects.isNull(sysUserInfo)) {
                return AjaxResult.warn("没有找到用户信息");
            }
            //获取出省市县的行政区代码
            String district = sysUserInfo.getDistrict();

            List<PreMuCompanyInfo> list = new ArrayList<>();
            List<PreMuCompanyInfo> updateList = new ArrayList<>();
            List<SysUser> sysUserArgs = new ArrayList<>();
            List<SysUser> updateSysUserArgs = new ArrayList<>();
            List<PreMuCompanyInfo> realList = new ArrayList<>();
            List<String> usccArgs = new ArrayList<>();

            StringBuilder failureMsg = new StringBuilder();
            long parkCount = preMuCompanyInfos.stream().filter(item -> !StringUtils.isEmpty(item.getZone())).count();
            if(parkCount > 0 && parkCount < preMuCompanyInfos.size()){
                return AjaxResult.warn("检测到有企业仍未填写园区，请重新完善园区后进行导入");
            }
            for (PreMuCompanyInfo item : preMuCompanyInfos) {
                String village = item.getVillage();
                if (village != null && village.trim().length() == 12) {
                    String county = village.trim().substring(0, 6);
                    if (!county.equals(district)) {
                        return AjaxResult.warn("不允许导入其他区县数据");
                    }
                    realList.add(item);
                    usccArgs.add(item.getUscc().trim());
                }else{
                    if(!StringUtils.isEmpty(village)){
                        String msg = "<br/>" +"企业 " + item.getCompanyName() + " 导入失败：";
                        failureMsg.append(msg + "所在街道乡镇只能用区划12位代码");
                        continue;
                    }

                }
                if (item.getIndustryType() == null || "".equals(item.getIndustryType())) {
                    String msg = "<br/>" +"企业 " + item.getCompanyName() + " 导入失败：";
                    failureMsg.append(msg + "所属行业大类不能为空");
                    continue;
                }
                if ("1".equals(item.getCompanyType())&&(item.getIndustryMediumType() == null || "".equals(item.getIndustryMediumType()))) {
                    String msg = "<br/>" +  "企业 " + item.getCompanyName() + " 导入失败：";
                    failureMsg.append(msg + "所属行业中类不能为空");
                    continue;
                }

                if (!item.getIndustryMediumType().substring(0, 2).equals(item.getIndustryType())) {
                    String msg = "<br/>" +  "企业 " + item.getCompanyName() + " 导入失败：";
                    failureMsg.append(msg + "->行业中类不属于行业大类，请检查导入数据！");
                    continue;
                }
                String evaluateByIndustry = item.getEvaluateByIndustry();
                if (StringUtils.isNotBlank(evaluateByIndustry) && !StrUtil.equalsAny(evaluateByIndustry, "是", "否")) {
                    String msg = "<br/>" +  "企业 " + item.getCompanyName() + " 导入失败：";
                    failureMsg.append(msg + "->是否按行业评价只能填是或者否！");
                    continue;
                }
            }
            if(!StringUtils.isEmpty(failureMsg)){
                return AjaxResult.warn(failureMsg.toString());
            }


            try {
                ValidationUtil.validate(realList);
            } catch (Exception e) {
                e.printStackTrace();
                if (e instanceof ValidationException) {
                    return AjaxResult.error(e.getMessage());
                }
                return AjaxResult.error("数据导入失败！");
            }

            long count = usccArgs.stream().distinct().count();
            boolean isRepeat = count < usccArgs.size();
            if (isRepeat) {
                return AjaxResult.error("有重复统一社会信用代码，请检查导入数据！");
            }

            List<PreMuCompanyInfo> dbCacheData = new ArrayList<>();
            if(StringUtils.equals(num,"1")){
                dbCacheData = preMuCompanyInfoMapper.selectPreMuCompanyInfoByUsccArgs(usccArgs,String.valueOf(year));
            }else if(StringUtils.equals(num,"2")){
                dbCacheData = preMuCompanyInfoNoMapper.selectPreMuCompanyInfoNoByUsccArgs(usccArgs,String.valueOf(year));
            }else{
                throw new RuntimeException("请指定导入参评或非参评企业");
            }

            Map<String, PreMuCompanyInfo> enterMap = new HashMap<>();
            if (dbCacheData != null && !dbCacheData.isEmpty()) {
                enterMap = dbCacheData.stream().collect(Collectors.toMap(k -> k.getUscc(), v -> v));
            }

            List<SysUser> currentUserNameExist = sysUserMapper.selectUserByUserNameArgs(usccArgs);
            Map<String, SysUser> userDataMap = currentUserNameExist.stream().collect(Collectors.toMap(k -> k.getUserName(), v -> v));

            for(PreMuCompanyInfo item : preMuCompanyInfos){
                String uscc = item.getUscc();
                if (uscc == null || "".equals(uscc)) {
                    continue;
                }else{
                    uscc = uscc.trim();
                }
                String village = item.getVillage();
                if (village != null && village.trim().length() == 12) {
                    String province = village.trim().substring(0, 2) + "0000";
                    String city = village.trim().substring(0, 4) + "00";
                    String county = village.trim().substring(0, 6);

                    //若为管理员导入,则-->设置区划为空
                    if (!StringUtils.equals(sysUserInfo.getUserId(),"1")) {
                        item.setProvince(province);
                        item.setCity(city);
                        item.setCounty(county);
                        item.setVillage(village.trim().substring(0, 9) + "000");
                    }
                } else {
                    return AjaxResult.error(item.getCompanyName() + " 统计用区划代码错误，请检查数据！");
                }
                item.setCompanyType(companyType);

                //防止规下覆盖规上企业校验
                PreMuCompanyInfo preMuCompanyInfo = enterMap.get(uscc);
                if (preMuCompanyInfo!=null){
                    if(StringUtils.equals(preMuCompanyInfo.getCompanyType(),"1") && StringUtils.equals(companyType,"2")){
                        return AjaxResult.error("【"+item.getCompanyName()+"】"+"已作为规上企业导入");
                    }
                }

                PreMuCompanyInfo dbCompanyInfo = new PreMuCompanyInfo();
                if(!enterMap.containsKey(uscc)){
                    dbCompanyInfo.setId(IdUtil.simpleUUID());
                    dbCompanyInfo.setUscc(uscc);
                    dbCompanyInfo.setCompanyName(item.getCompanyName());
                    dbCompanyInfo.setCompanyType(item.getCompanyType());
                    dbCompanyInfo.setProvince(item.getProvince());
                    dbCompanyInfo.setCity(item.getCity());
                    dbCompanyInfo.setCounty(item.getCounty());
                    dbCompanyInfo.setVillage(item.getVillage());
                    dbCompanyInfo.setDelFlag("0");
                    dbCompanyInfo.setYear(String.valueOf(year));
                    dbCompanyInfo.setModuleType(getModuleType(moduleType));
                    dbCompanyInfo.setCreateBy(SecurityUtils.getUserId());
                    dbCompanyInfo.setCreateDate(DateUtils.getNowDate());
                    String zone = item.getZone();
                    if(StringUtils.isNotBlank(zone)){
                        dbCompanyInfo.setZone(item.getZone());
                    }
                    dbCompanyInfo.setEvaluateByIndustry(item.getEvaluateByIndustry());
                    dbCompanyInfo.setIndustryType(item.getIndustryType());
                    dbCompanyInfo.setIndustryMediumType(item.getIndustryMediumType());
                    list.add(dbCompanyInfo);
                }else{
                    PreMuCompanyInfo preMuCompanyInfo1 = enterMap.get(uscc);
                    dbCompanyInfo.setUscc(uscc);
                    dbCompanyInfo.setId(preMuCompanyInfo1.getId());
                    dbCompanyInfo.setCompanyName(item.getCompanyName());
                    dbCompanyInfo.setCompanyType(item.getCompanyType());
                    dbCompanyInfo.setProvince(item.getProvince());
                    dbCompanyInfo.setCity(item.getCity());
                    dbCompanyInfo.setCounty(item.getCounty());
                    dbCompanyInfo.setVillage(item.getVillage());
                    dbCompanyInfo.setYear(String.valueOf(year));
                    //根据数据表存在的module_type和moduleSign获取最终的moduleType的值
                    String oldModuleType = (String) preMuCompanyInfo1.getModuleType();
                    String moduleTypeNew = incModuleType(moduleType, oldModuleType);
                    dbCompanyInfo.setModuleType(moduleTypeNew);
                    dbCompanyInfo.setDelFlag("0");
                    String zone = item.getZone();
                    if(StringUtils.isNotBlank(zone)){
                        dbCompanyInfo.setZone(item.getZone());
                    }
                    dbCompanyInfo.setEvaluateByIndustry(item.getEvaluateByIndustry());
                    dbCompanyInfo.setIndustryType(item.getIndustryType());
                    dbCompanyInfo.setIndustryMediumType(item.getIndustryMediumType());
                    updateList.add(dbCompanyInfo);
                }

                SysUser sysUser = new SysUser();
                if(!userDataMap.containsKey(uscc)){
                    sysUser.setUserId(IdUtil.simpleUUID());
                    sysUser.setUserName(uscc);
                    sysUser.setNickName(dbCompanyInfo.getCompanyName());
//                    sysUser.setPassword(SecurityUtils.encryptPassword(StrUtil.subSuf(uscc,-8)));
                    sysUser.setPassword(MD5Utils.encrypt(uscc,StrUtil.subSuf(uscc,-8)));
                    sysUser.setStatus("0");
                    sysUser.setDelFlag("0");
                    sysUser.setProvince(dbCompanyInfo.getProvince());
                    sysUser.setCity(dbCompanyInfo.getCity());
                    sysUser.setDistrict(dbCompanyInfo.getCounty());
                    sysUserArgs.add(sysUser);
                }else{
                    SysUser sysUser1 = userDataMap.get(uscc);
                    sysUser.setUserName(uscc);
                    sysUser.setUserId(sysUser1.getUserId());
                    sysUser.setNickName(item.getCompanyName());
                    sysUser.setPassword(MD5Utils.encrypt(uscc,StrUtil.subSuf(uscc,-8)));
                    sysUser.setStatus("0");
                    sysUser.setProvince(item.getProvince());
                    sysUser.setCity(item.getCity());
                    sysUser.setDistrict(item.getCounty());
                    updateSysUserArgs.add(sysUser);
                }

                if(list.size() >= BACTH_COUNT){
                    //导入参评企业
                    if(StringUtils.equals(num,"1")){
                        preMuCompanyInfoMapper.batchPreMuCompanyInfoData(list);
                    }else if(StringUtils.equals(num,"2")){
                        //导入不参评企业
                        preMuCompanyInfoNoMapper.batchPreMuCompanyInfoNoData(list);
                    }
                    list.clear();
                }

                if(updateList.size() >= BACTH_COUNT){

                    //导入参评企业
                    if(StringUtils.equals(num,"1")){
                        preMuCompanyInfoMapper.batchUpdatePreMuCompanyInfoData(updateList);
                    }else if(StringUtils.equals(num,"2")){
                        //导入不参评企业
                        preMuCompanyInfoNoMapper.batchUpdatePreMuCompanyInfoNoData(updateList);
                    }
                    updateList.clear();
                }

                if(sysUserArgs.size() >= BACTH_COUNT){
                    sysUserMapper.batchInsertUser(sysUserArgs);
                    batchSaveUserRoleInfo(sysUserArgs);
                    sysUserArgs.clear();
                }

                if(updateSysUserArgs.size() >= BACTH_COUNT){
                    sysUserMapper.batchUpdateUser(updateSysUserArgs);
                    updateSysUserArgs.clear();
                }
            }


            if(!list.isEmpty()){
                //导入参评企业
                if(StringUtils.equals(num,"1")){
                    preMuCompanyInfoMapper.batchPreMuCompanyInfoData(list);
                }else if(StringUtils.equals(num,"2")){
                    //导入不参评企业
                    preMuCompanyInfoNoMapper.batchPreMuCompanyInfoNoData(list);
                }
                list.clear();
            }

            if(!updateList.isEmpty()){
                //导入参评企业
                if(StringUtils.equals(num,"1")){
                    preMuCompanyInfoMapper.batchUpdatePreMuCompanyInfoData(updateList);
                }else if(StringUtils.equals(num,"2")){
                    //导入不参评企业
                    preMuCompanyInfoNoMapper.batchUpdatePreMuCompanyInfoNoData(updateList);
                }
                updateList.clear();
            }

            if(!sysUserArgs.isEmpty()){
                sysUserMapper.batchInsertUser(sysUserArgs);
                batchSaveUserRoleInfo(sysUserArgs);
                sysUserArgs.clear();
            }

            if(!updateSysUserArgs.isEmpty()){
                sysUserMapper.batchUpdateUser(updateSysUserArgs);
                updateSysUserArgs.clear();
            }



        }catch (Exception e){
            String requestURI = prams.get("url");
            SysOperError sysOperError = new SysOperError();
            sysOperError.setBaseId(IdUtil.simpleUUID());
            sysOperError.setBaseCreateTime(new Date());
            sysOperError.setErrorMsg(e.getMessage());
            sysOperError.setUrlAddress(requestURI);
            sysOperError.setOperId(SecurityUtils.getUserId());
            sysOperErrorMapper.saveErrorInfo(sysOperError);
            System.out.println(e.getMessage());
            throw new RuntimeException("导入失败："+e.getMessage());
        }
        return AjaxResult.success("保存成功");
    }



    /**
     * <p>
     *     批量保存用户与角色的关系
     * </p>
     * @param sysUserArgs
     */
    private void batchSaveUserRoleInfo(List<SysUser> sysUserArgs){
        if(sysUserArgs == null || sysUserArgs.isEmpty()){
            return;
        }
        List<SysUserRole> sysUserRoleList = new ArrayList<>();
        for(SysUser item : sysUserArgs){
            SysUserRole temp = new SysUserRole();
            temp.setUserId(item.getUserId());
            temp.setRoleId("1ae0bb3bd1c3420a814de76b2c154ab0");
            sysUserRoleList.add(temp);
            if(sysUserRoleList.size() > BACTH_COUNT){
                sysUserRoleMapper.batchUserRole(sysUserRoleList);
                sysUserRoleList.clear();
            }
        }
        if(!sysUserRoleList.isEmpty()){
            sysUserRoleMapper.batchUserRole(sysUserRoleList);
            sysUserRoleList.clear();
        }
    }

    private String incModuleType(String moduleSign, String oldModuleType){
        Integer start = 0;
        if("B".equals(moduleSign)){
            start = 1;
        }
        return StrUtil.replace(oldModuleType, start,start + 1, '1');
    }

    private String getModuleType(String moduleSign){
        if("A".equals(moduleSign)){
            return "10";
        }
        if("B".equals(moduleSign)){
            return "01";
        }
        return "";
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult deleteCompanyInfo(Map<String,String> params) {

        if(StringUtils.isBlank(params.get("num"))){
            return AjaxResult.warn("没有找到Num");
        }

        if(StringUtils.isBlank(params.get("ids"))){
            return AjaxResult.warn("没有找到要删除的数据");
        }

        String[] ids = params.get("ids").split(",");

        if(StringUtils.equals(params.get("num"),"1")){

            int count = preMuBenefitEvaluationMapper.getCountByIds(ids);
            if(count > 0){
                return AjaxResult.error("删除的部分企业已汇入到评价结果中无法删除");
            }

            List<PreMuCompanyInfo> result = preMuCompanyInfoMapper.selectPreMuCompanyInfoByIds(ids);
            if(result != null && !result.isEmpty()){
                List<String> usccArgs = result.stream().map(PreMuCompanyInfo::getUscc).collect(Collectors.toList());
                //查询用户的信息
                List<SysUser> sysUsers = sysUserMapper.selectUserByUserNameArgs(usccArgs);
                if(sysUsers != null && !sysUsers.isEmpty()){
                    List<String> userIdArgs = sysUsers.stream().map(SysUser::getUserId).collect(Collectors.toList());
                    sysUserMapper.deleteUserByUserName(usccArgs);
                    sysUserRoleMapper.deleteUserRoleInfos("1ae0bb3bd1c3420a814de76b2c154ab0",userIdArgs.toArray(new String[userIdArgs.size()]));
                }
            }
            preMuCompanyInfoMapper.deletePreMuCompanyInfoByIds(ids);
            return AjaxResult.success();
        } else if (StringUtils.equals(params.get("num"),"2")) {

            int count = preMuBenefitEvaluationNoMapper.getCountByIds(ids);
            if(count > 0){
                return AjaxResult.error("删除的部分企业已经汇入评价结果,无法删除");
            }

            List<PreMuCompanyInfo> result = preMuCompanyInfoMapper.selectPreMuCompanyInfoByIds(ids);
            if(result != null && !result.isEmpty()){
                List<String> usccArgs = result.stream().map(PreMuCompanyInfo::getUscc).collect(Collectors.toList());
                //查询用户的信息
                List<SysUser> sysUsers = sysUserMapper.selectUserByUserNameArgs(usccArgs);
                if(sysUsers != null && !sysUsers.isEmpty()){
                    List<String> userIdArgs = sysUsers.stream().map(SysUser::getUserId).collect(Collectors.toList());
                    sysUserMapper.deleteUserByUserName(usccArgs);
                    //删除用户相关角色
                    sysUserRoleMapper.deleteUserRoleInfos("1ae0bb3bd1c3420a814de76b2c154ab0",userIdArgs.toArray(new String[userIdArgs.size()]));
                }
            }
            preMuCompanyInfoNoMapper.deletePreMuCompanyInfoNoByIds(ids);
            return AjaxResult.success();
        }
        return AjaxResult.warn("没有找到相应Num");
    }


    /**
     * 删除不参评企业
     *
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult deleteCompanyInfoNo(Map<String, String> params) {

        LocalDate localDate = LocalDate.now();
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        int noCount = preMuBenefitEvaluationNoMapper.selectDataCount(String.valueOf(localDate.getYear() - 1),params.get("compnyType"),sysUser.getDistrict());

        if(noCount > 0){
            return AjaxResult.error("该企业类型的数据已汇入完法删除");
        }

        if(StringUtils.isBlank(params.get("compnyType"))){
            return AjaxResult.warn("没有找到企业类型");
        }


        PreMuCompanyInfoNo param = new PreMuCompanyInfoNo();
        param.setCompanyType(params.get("compnyType"));


        param.setYear(String.valueOf(localDate.getYear() - 1));
        param.setCounty(sysUser.getDistrict());

        List<PreMuCompanyInfoNo> preMuCompanyInfoNos = preMuCompanyInfoNoMapper.selectPreMuCompanyInfoNoList(param);
        if(preMuCompanyInfoNos != null && !preMuCompanyInfoNos.isEmpty()){
            //获取出企业的USCC，通过删除用户通过user_name
            List<String> usccArgs = preMuCompanyInfoNos.stream().map(PreMuCompanyInfoNo::getUscc).collect(Collectors.toList());
            sysUserMapper.deleteUserByUserName(usccArgs);

            String deleteIdStr = preMuCompanyInfoNos.stream().map(PreMuCompanyInfoNo::getId).collect(Collectors.joining(","));
            String[] deleteIdArgs = deleteIdStr.split(",");
            preMuCompanyInfoNoMapper.deletePreMuCompanyInfoNoByIds(deleteIdArgs);

        }
        return AjaxResult.success();
    }

    /**
     * 删除参评企业
     *
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult deleteCompanyInfoCp(Map<String, String> params) {
        if(StringUtils.isBlank(params.get("compnyType"))){
            return AjaxResult.warn("没有找到企业类型");
        }
        LocalDate localDate = LocalDate.now();
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        int count = preMuBenefitEvaluationMapper.selectDataCount(String.valueOf(localDate.getYear() - 1), params.get("compnyType"), sysUser.getDistrict());
        if(count > 0){
            return AjaxResult.error("当前企业类型已汇入，无法删除");
        }

        PreMuCompanyInfo param = new PreMuCompanyInfo();


        param.setYear(String.valueOf(localDate.getYear() - 1));
        param.setCounty(sysUser.getDistrict());
        param.setCompanyType(params.get("compnyType"));
        List<PreMuCompanyInfo> preMuCompanyInfoNos = preMuCompanyInfoMapper.selectPreMuCompanyInfoList(param);
        if(preMuCompanyInfoNos != null && !preMuCompanyInfoNos.isEmpty()){
            //获取出企业的USCC，通过删除用户通过user_name
            List<String> usccArgs = preMuCompanyInfoNos.stream().map(PreMuCompanyInfo::getUscc).collect(Collectors.toList());
            sysUserMapper.deleteUserByUserName(usccArgs);

            String deleteIdStr = preMuCompanyInfoNos.stream().map(PreMuCompanyInfo::getId).collect(Collectors.joining(","));
            String[] deleteIdArgs = deleteIdStr.split(",");
            preMuCompanyInfoMapper.deletePreMuCompanyInfoByIds(deleteIdArgs);

        }
        return AjaxResult.success();
    }

    private Map<String,String> modelMap = new HashMap<>();

    @PostConstruct
    public void init(){
        modelMap.put("A","10");
        modelMap.put("B","01");
    }

    /**
     * 删除模块
     *
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult deleteMode(Map<String, String> params) {
        if(StringUtils.isBlank(params.get("num"))){
            return AjaxResult.warn("没有找到Num");
        }

        if(StringUtils.isBlank(params.get("ids"))){
            return AjaxResult.warn("没有找到要删除的数据");
        }
        String companyModel = "";
        if(StringUtils.isBlank(companyModel = params.get("companyModel"))){
            return AjaxResult.warn("没有找到要删除的模块");
        }
        companyModel = modelMap.get(companyModel);
        String[] ids = params.get("ids").split(",");

         List<String> userNameArgs = new ArrayList<>();
         //需要更新的数据  参评
        List<PreMuCompanyInfo> updateCpModeInfo = new ArrayList<>();
        List<PreMuCompanyInfo> deleteCpCompanyInfo = new ArrayList<>();
        //不参评
        List<PreMuCompanyInfoNo> updateNoCpModeInfo = new ArrayList<>();
        List<PreMuCompanyInfoNo> deleteNoCpCompanyInfo = new ArrayList<>();
        if(StringUtils.equals(params.get("num"),"1")){
            List<PreMuCompanyInfo> result = preMuCompanyInfoMapper.selectPreMuCompanyInfoByIds(ids);

            for(PreMuCompanyInfo item : result){
                String moduleType = item.getModuleType();
                //运行监测、亩产
                if(StringUtils.equals(moduleType,"11")){
                    if(StringUtils.equals(companyModel,"10")){
                        PreMuCompanyInfo temp = new PreMuCompanyInfo();
                        temp.setModuleType("01");
                        temp.setId(item.getId());
                        updateCpModeInfo.add(temp);
                    } else if (StringUtils.equals(companyModel,"01")) {
                        PreMuCompanyInfo temp = new PreMuCompanyInfo();
                        temp.setModuleType("10");
                        temp.setId(item.getId());
                        updateCpModeInfo.add(temp);
                    }
                } else if (StringUtils.equals(moduleType,"10") && StringUtils.equals(companyModel,"10")) {
                    //亩产
                    PreMuCompanyInfo temp =new PreMuCompanyInfo();
                    temp.setId(item.getId());
                    deleteCpCompanyInfo.add(temp);
                    userNameArgs.add(item.getUscc());
                }else if (StringUtils.equals(moduleType,"01") && StringUtils.equals(companyModel,"01")) {
                    //运行监测
                    PreMuCompanyInfo temp =new PreMuCompanyInfo();
                    temp.setId(item.getId());
                    deleteCpCompanyInfo.add(temp);
                    userNameArgs.add(item.getUscc());
                }

                if(userNameArgs.size() >= BACTH_COUNT){
                    sysUserMapper.deleteUserByUserName(userNameArgs);
                    userNameArgs.clear();
                }

                if(updateCpModeInfo.size() >= BACTH_COUNT){
                    preMuCompanyInfoMapper.batchUpdatePreMuCompanyInfoData(updateCpModeInfo);
                    updateCpModeInfo.clear();
                }

                if(deleteCpCompanyInfo.size() >= BACTH_COUNT){
                    String collect = deleteCpCompanyInfo.stream().map(PreMuCompanyInfo::getId).collect(Collectors.joining(","));
                    preMuCompanyInfoMapper.deletePreMuCompanyInfoByIds(collect.split(","));
                    updateCpModeInfo.clear();
                }
            }

            if(!userNameArgs.isEmpty()){
                sysUserMapper.deleteUserByUserName(userNameArgs);
                userNameArgs.clear();
            }

            if(!updateCpModeInfo.isEmpty()){
                preMuCompanyInfoMapper.batchUpdatePreMuCompanyInfoData(updateCpModeInfo);
                updateCpModeInfo.clear();
            }

            if(!deleteCpCompanyInfo.isEmpty()){
                String collect = deleteCpCompanyInfo.stream().map(PreMuCompanyInfo::getId).collect(Collectors.joining(","));
                preMuCompanyInfoMapper.deletePreMuCompanyInfoByIds(collect.split(","));
                updateCpModeInfo.clear();
            }
            return AjaxResult.success();
        } else if (StringUtils.equals(params.get("num"),"2")) {
            List<PreMuCompanyInfoNo> result = preMuCompanyInfoNoMapper.selectPreMuCompanyInfoNoByIds(ids);
            for(PreMuCompanyInfoNo item : result){
                String moduleType = item.getModuleType();
                //运行监测、亩产
                if(StringUtils.equals(moduleType,"11")){
                    if(StringUtils.equals(companyModel,"10")){
                        PreMuCompanyInfoNo temp = new PreMuCompanyInfoNo();
                        temp.setModuleType("01");
                        temp.setId(item.getId());
                        updateNoCpModeInfo.add(temp);
                    } else if (StringUtils.equals(companyModel,"01")) {
                        PreMuCompanyInfoNo temp = new PreMuCompanyInfoNo();
                        temp.setModuleType("10");
                        temp.setId(item.getId());
                        updateNoCpModeInfo.add(temp);
                    }
                } else if (StringUtils.equals(moduleType,"10") && StringUtils.equals(companyModel,"10")) {
                    //亩产
                    PreMuCompanyInfoNo temp =new PreMuCompanyInfoNo();
                    temp.setId(item.getId());
                    deleteNoCpCompanyInfo.add(temp);
                    userNameArgs.add(item.getUscc());
                }else if (StringUtils.equals(moduleType,"01") && StringUtils.equals(companyModel,"01")) {
                    //运行监测
                    PreMuCompanyInfoNo temp =new PreMuCompanyInfoNo();
                    temp.setId(item.getId());
                    deleteNoCpCompanyInfo.add(temp);
                    userNameArgs.add(item.getUscc());
                }

                if(userNameArgs.size() >= BACTH_COUNT){
                    sysUserMapper.deleteUserByUserName(userNameArgs);
                    userNameArgs.clear();
                }

                if(updateNoCpModeInfo.size() >= BACTH_COUNT){

                    List<PreMuCompanyInfo> collect = updateNoCpModeInfo.stream().map(items -> {
                        PreMuCompanyInfo p = new PreMuCompanyInfo();
                        BeanUtil.copyProperties(items, p);
                        return p;
                    }).collect(Collectors.toList());

                    preMuCompanyInfoNoMapper.batchUpdatePreMuCompanyInfoNoData(collect);
                    updateNoCpModeInfo.clear();
                }

                if(deleteNoCpCompanyInfo.size() >= BACTH_COUNT){
                    String collect = deleteNoCpCompanyInfo.stream().map(PreMuCompanyInfoNo::getId).collect(Collectors.joining(","));
                    preMuCompanyInfoNoMapper.deletePreMuCompanyInfoNoByIds(collect.split(","));
                    deleteNoCpCompanyInfo.clear();
                }
            }

            if(!userNameArgs.isEmpty()){
                sysUserMapper.deleteUserByUserName(userNameArgs);
                userNameArgs.clear();
            }

            if(!updateNoCpModeInfo.isEmpty()){
                List<PreMuCompanyInfo> collect = updateNoCpModeInfo.stream().map(items -> {
                    PreMuCompanyInfo p = new PreMuCompanyInfo();
                    BeanUtil.copyProperties(items, p);
                    return p;
                }).collect(Collectors.toList());

                preMuCompanyInfoNoMapper.batchUpdatePreMuCompanyInfoNoData(collect);
                updateNoCpModeInfo.clear();
            }

            if(!deleteCpCompanyInfo.isEmpty()){
                String collect = deleteCpCompanyInfo.stream().map(PreMuCompanyInfo::getId).collect(Collectors.joining(","));
                preMuCompanyInfoNoMapper.deletePreMuCompanyInfoNoByIds(collect.split(","));
                updateCpModeInfo.clear();
            }
            return AjaxResult.success();
        }

        return AjaxResult.warn("没有找到相应Num");
    }

    @Override
    public AjaxResult resetPassword(Map<String, String> params) {
        String num = null;
        String ids = null;
        if(StringUtils.isBlank(num = params.get("num")) ||
                StringUtils.isBlank(ids = params.get("ids"))){
            return AjaxResult.warn("没有找到num或者企业的唯一标识");
        }

        if(StringUtils.equals(num,"1")){
            PreMuCompanyInfo preMuCompanyInfo = preMuCompanyInfoMapper.selectPreMuCompanyInfoById(ids);
            String uscc = preMuCompanyInfo.getUscc();
            SysUser sysUser = new SysUser();
            sysUser.setUserName(uscc);
//            sysUser.setPassword(SecurityUtils.encryptPassword(StrUtil.subSuf(uscc,-8)));
            sysUser.setPassword(MD5Utils.encrypt(uscc,StrUtil.subSuf(uscc,-8)));
            sysUserMapper.updateUserPassword(sysUser);
            return AjaxResult.success();
        } else if (StringUtils.equals(num,"2")) {
            PreMuCompanyInfoNo preMuCompanyInfoNo = preMuCompanyInfoNoMapper.selectPreMuCompanyInfoNoById(ids);
            String uscc = preMuCompanyInfoNo.getUscc();
            SysUser sysUser = new SysUser();
            sysUser.setUserName(uscc);
//            sysUser.setPassword(SecurityUtils.encryptPassword(StrUtil.subSuf(uscc,-8)));
            sysUser.setPassword(MD5Utils.encrypt(uscc,StrUtil.subSuf(uscc,-8)));
            sysUserMapper.updateUserPassword(sysUser);
            return AjaxResult.success();
        }
        return AjaxResult.warn("报错了");
    }

    @Override
    public List<PreMuCompanyInfo> list(PreMuCompanyInfo companyInfoQueryParams) {
        List<PreMuCompanyInfo> redsult = preMuCompanyInfoMapper.list(companyInfoQueryParams);
        return redsult;
    }

    @Override
    public PreMuCompanyInfo selectPreMuCompanyInfoByUscc(String uscc) {
        return  preMuCompanyInfoMapper.selectPreMuCompanyInfoByUscc(uscc);
    }

    @Override
    public PreMuCompanyInfo getById(String id) {
        return preMuCompanyInfoMapper.selectPreMuCompanyInfoById(id);
    }

    /**
     * <p>
     *     查询旧的企业信息
     * </p>
     *
     * @param userName 这个UserName是企业的社会统一信用代码
     * @return 企业信息
     */
    @Override
    public PreMuCompanyInfo queryOldCompanyInfo(String userName) {
        if(StringUtils.isBlank(userName)){
            throw new RuntimeException("没有找到企业的统一社会信用代码");
        }
        PreMuCompanyInfo preMuCompanyInfo = preMuCompanyInfoMapper.selectPreMuCompanyInfoByUscc(userName);
        if(preMuCompanyInfo == null){
            preMuCompanyInfo = new PreMuCompanyInfo();
            PreMuCompanyInfoNo preMuCompanyInfoNo = preMuCompanyInfoNoMapper.selectPreMuCompanyInfoNoByUscc(userName);
            if(preMuCompanyInfoNo == null){
                throw new RuntimeException("未找到企业信息");
            }
            BeanUtil.copyProperties(preMuCompanyInfoNo,preMuCompanyInfo);
            preMuCompanyInfo.setCreateDate(DateUtils.getNowDate());
        }else{
            preMuCompanyInfo.setCreateDate(DateUtils.getNowDate());
        }

        return preMuCompanyInfo;
    }

    /**
     * @return
     */
    @Override
    public List<PreMuJszxHy> getJszx_hy() {
        return preMuCompanyInfoNoMapper.getJszx_hy();
    }

    /**
     * @param dl
     * @return
     */
    @Override
    public List<PreMuStandardIndustryInfo> getStandard(String dl) {

        return preMuCompanyInfoNoMapper.getStandard(dl);
    }

    /**
     * 通过uscc查询企业ID
     *
     * @param uscc
     * @return
     */
    @Override
    public String selectEnterCompanyId(String uscc) {
        List<String> companyIds = preMuCompanyInfoMapper.selectCompanyIdInfoByUscc(uscc);
        if(companyIds != null && !companyIds.isEmpty()){
            return companyIds.get(0);
        }
        return null;
    }

    @Override
    public AjaxResult zoneList(PreMuCompanyInfo preMuCompanyInfo, String calFlag) {
        List<String> zoneList = new ArrayList<>();
        if("1".equals(calFlag)){
            PreMuIndexWeightMain preMuIndexWeightMain = new PreMuIndexWeightMain();
            preMuIndexWeightMain.setCompanyType(preMuCompanyInfo.getCompanyType());
            preMuIndexWeightMain.setCounty(preMuCompanyInfo.getCounty());
            preMuIndexWeightMain.setYear(preMuCompanyInfo.getYear());
            List<PreMuIndexWeightMain> preMuIndexWeightMains = preMuIndexWeightMainMapper.selectPreMuIndexWeightMainListNew(preMuIndexWeightMain);
            if(!CollectionUtils.isEmpty(preMuIndexWeightMains)){
                List<String> list = preMuIndexWeightMains.stream().filter(f -> !StringUtils.isEmpty(f.getPark())).map(m -> m.getPark()).collect(Collectors.toList());
                if(!CollectionUtils.isEmpty(list)){
                    for (String zones : list) {
                        List<String> splitList = Arrays.stream(zones.split(",")).collect(Collectors.toList());
                        zoneList.addAll(splitList);
                    }
                }
            }
        }else{
            zoneList = preMuCompanyInfoMapper.zoneList(preMuCompanyInfo);
        }
        return AjaxResult.success(zoneList);
    }

    @Override
    public AjaxResult industryList(PreMuCompanyInfo preMuCompanyInfo, String calFlag) {
        List<Map> industryList = new ArrayList<>();
        if("1".equals(calFlag)){
            PreMuIndexWeightMain preMuIndexWeightMain = new PreMuIndexWeightMain();
            preMuIndexWeightMain.setCompanyType(preMuCompanyInfo.getCompanyType());
            preMuIndexWeightMain.setCounty(preMuCompanyInfo.getCounty());
            preMuIndexWeightMain.setYear(preMuCompanyInfo.getYear());
            List<PreMuIndexWeightMain> preMuIndexWeightMains = preMuIndexWeightMainMapper.selectPreMuIndexWeightMainListNew(preMuIndexWeightMain);
            if(!CollectionUtils.isEmpty(preMuIndexWeightMains)){
                List<PreMuIndexWeightMain> industrys = preMuIndexWeightMains.stream().filter(f->!StringUtils.isEmpty(f.getIndustry())).collect(Collectors.toList());
                if(!CollectionUtils.isEmpty(industrys)){
                    for (PreMuIndexWeightMain main : industrys) {
                        List<String> codeList = Arrays.stream(main.getIndustry().split(",")).collect(Collectors.toList());
                        List<String> nameList = Arrays.stream(main.getIndustryName().split(",")).collect(Collectors.toList());
                        for (int i =0; i < codeList.size(); i++) {
                            Map map = new HashMap();
                            map.put("industry", codeList.get(i));
                            map.put("industryName", nameList.get(i));
                            industryList.add(map);
                        }

                    }


                }
            }
        }else{
            industryList = preMuCompanyInfoMapper.industryList(preMuCompanyInfo);
        }
        return AjaxResult.success(industryList);
    }


    @Override
    public AjaxResult saveCompanyInfoThird(PreMuCompanyInfoThirdDto dto) {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(8);
        executor.setMaxPoolSize(8);
        executor.setQueueCapacity(1000);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setThreadNamePrefix("company-processor-");
        executor.initialize();


        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
        transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        transactionTemplate.setTimeout(60 * 60);

        List<PreMuCompanyInfo> companyList = dto.getCompanyList();


        int parkCount = 0;
        List<String> usccList = new ArrayList();
        for (PreMuCompanyInfo item : companyList) {
            if(!StringUtils.isEmpty(item.getZone())){
                parkCount++;
            }
            if(!StringUtils.isEmpty(item.getUscc())){
                usccList.add(item.getUscc());
            }
        }
        if(parkCount > 0 && parkCount < companyList.size()){
            return AjaxResult.warn("检测到该区县有企业仍未填写园区，请重新完善园区后进行添加");
        }

        return transactionTemplate.execute(status -> {
            try {


                Map<String, PreMuCompanyInfo> mcImportExistMap = loadExistRecords(dto, usccList);

                List<CompletableFuture<ProcessCompanyInfoVo>> futures = new ArrayList<>();

                if(!CollectionUtils.isEmpty(companyList)){
                    List<List<PreMuCompanyInfo>> lists = splitIntoBatches(companyList, BATCH_SIZE);
                    for (List<PreMuCompanyInfo> dataList : lists) {

                        final List<PreMuCompanyInfo> countyData = dataList;

                        futures.add(CompletableFuture.supplyAsync(() ->
                                        processCountyData(countyData, mcImportExistMap, dto),
                                executor
                        ));


                    }
                    List<PreMuCompanyInfo> allAddList = new ArrayList<>();
                    List<PreMuCompanyInfo> allUpdateList = new ArrayList<>();
                    List<SysUser> allAddUserList = new ArrayList<>();
                    List<SysUser> allUpdateUserList = new ArrayList<>();
                    List<String> allErrorList = new ArrayList<>();

                    for (CompletableFuture<ProcessCompanyInfoVo> future : futures) {
                        ProcessCompanyInfoVo result = future.get(30, TimeUnit.MINUTES);
                        allErrorList.addAll(result.getErrorList());
                    }
                    if(!CollectionUtils.isEmpty(allErrorList)){
                        throw new ServiceException(String.valueOf(allErrorList));
                    }
                    for (CompletableFuture<ProcessCompanyInfoVo> future : futures) {
                        ProcessCompanyInfoVo result = future.get(30, TimeUnit.MINUTES);
                        allAddList.addAll(result.getAddList());
                        allUpdateList.addAll(result.getUpdateList());
                        allAddUserList.addAll(result.getAddUserList());
                        allUpdateUserList.addAll(result.getUpdateUserList());


                        if (allAddList.size() >= BATCH_SIZE) {
                            batchInsert(allAddList, dto.getEvaluationFlag());
                            allAddList.clear();
                        }
                        if (allUpdateList.size() >= BATCH_SIZE) {
                            batchUpdate(allUpdateList, dto.getEvaluationFlag());
                            allUpdateList.clear();
                        }
                        if (allAddUserList.size() >= BATCH_SIZE) {
                            batchUpdateUser(allAddUserList);
                            allAddList.clear();
                        }
                        if (allUpdateUserList.size() >= BATCH_SIZE) {
                            batchUpdateUser(allUpdateUserList);
                            allUpdateList.clear();
                        }
                    }


                    if (!allAddList.isEmpty()) batchInsert(allAddList, dto.getEvaluationFlag());
                    if (!allUpdateList.isEmpty()) batchUpdate(allUpdateList, dto.getEvaluationFlag());
                    if (!allAddUserList.isEmpty()) batchInsertUser(allAddUserList);
                    if (!allUpdateUserList.isEmpty()) batchUpdateUser(allUpdateUserList);

                }


            } catch (ServiceException e) {
                status.setRollbackOnly();
                return AjaxResult.warn(e.getMessage());
            } catch (TimeoutException e) {
                status.setRollbackOnly();
                return AjaxResult.error("处理超时，已回滚事务");
            } catch (Exception e) {
                status.setRollbackOnly();
                return AjaxResult.error("处理失败，已回滚事务");
            } finally {
                executor.shutdown();

            }

            return AjaxResult.success();
        });

    }


    private Map<String, PreMuCompanyInfo> loadExistRecords(PreMuCompanyInfoThirdDto dto, List<String> usccList) {
        String year = dto.getYear();
        List<PreMuCompanyInfo> dbCacheData = new ArrayList<>();
        if(StringUtils.equals(dto.getEvaluationFlag(),"1")){
            dbCacheData = preMuCompanyInfoMapper.selectPreMuCompanyInfoByUsccArgs(usccList, year);
        }else if(StringUtils.equals(dto.getEvaluationFlag(),"2")){
            dbCacheData = preMuCompanyInfoNoMapper.selectPreMuCompanyInfoNoByUsccArgs(usccList, year);
        }

        Map<String, PreMuCompanyInfo> enterMap = new HashMap<>();
        if (dbCacheData != null && !dbCacheData.isEmpty()) {
            enterMap = dbCacheData.stream().collect(Collectors.toMap(k -> k.getUscc(), v -> v));
        }
        return enterMap;
    }


    private ProcessCompanyInfoVo processCountyData(
            List<PreMuCompanyInfo> countyData,
            Map<String, PreMuCompanyInfo> existRecordMap,
            PreMuCompanyInfoThirdDto dto) {

        List<PreMuCompanyInfo> addList = new ArrayList<>();
        List<PreMuCompanyInfo> updateList = new ArrayList<>();
        List<SysUser> addUserList = new ArrayList<>();
        List<SysUser> updateUserList = new ArrayList<>();

        List<String> errorList = new ArrayList<>();
        List<String> usccArgs = countyData.stream().map(m -> m.getUscc()).collect(Collectors.toList());
        List<SysUser> currentUserNameExist = sysUserMapper.selectUserByUserNameArgs(usccArgs);
        Map<String, SysUser> userDataMap = currentUserNameExist.stream().collect(Collectors.toMap(k -> k.getUserName(), v -> v));

        for (PreMuCompanyInfo data : countyData) {
            String uscc = data.getUscc();
            String village = data.getVillage();
            if (village != null && village.trim().length() == 12) {
                String province = village.trim().substring(0, 2) + "0000";
                String city = village.trim().substring(0, 4) + "00";
                String county = village.trim().substring(0, 6);

                //若为管理员导入,则-->设置区划为空
                data.setProvince(province);
                data.setCity(city);
                data.setCounty(county);
                data.setVillage(village.trim().substring(0, 9) + "000");
            } else {
                errorList.add(data.getCompanyName() + " 统计用区划代码错误，请检查数据！");
            }
            //防止规下覆盖规上企业校验
            PreMuCompanyInfo preMuCompanyInfo = existRecordMap.get(data.getUscc());
            if (preMuCompanyInfo!=null){
                if(StringUtils.equals(preMuCompanyInfo.getCompanyType(),"1") && StringUtils.equals(dto.getCompanyType(),"2")){
                    errorList.add("【"+data.getCompanyName()+"】"+"已作为规上企业添加");
                }
            }
            PreMuCompanyInfo dbCompanyInfo = new PreMuCompanyInfo();
            dbCompanyInfo.setCompanyType(dto.getCompanyType());
            if(!existRecordMap.containsKey(uscc)){
                dbCompanyInfo.setId(IdUtil.simpleUUID());
                dbCompanyInfo.setUscc(uscc);
                dbCompanyInfo.setCompanyName(data.getCompanyName());
                dbCompanyInfo.setProvince(data.getProvince());
                dbCompanyInfo.setCity(data.getCity());
                dbCompanyInfo.setCounty(data.getCounty());
                dbCompanyInfo.setVillage(data.getVillage());
                dbCompanyInfo.setDelFlag("0");
                dbCompanyInfo.setYear(dto.getYear());
                dbCompanyInfo.setModuleType("10");
                dbCompanyInfo.setCreateBy(SecurityUtils.getUserId());
                dbCompanyInfo.setCreateDate(DateUtils.getNowDate());
                String zone = data.getZone();
                if(StringUtils.isNotBlank(zone)){
                    dbCompanyInfo.setZone(data.getZone());
                }
                dbCompanyInfo.setEvaluateByIndustry(data.getEvaluateByIndustry());
                dbCompanyInfo.setIndustryType(data.getIndustryType());
                dbCompanyInfo.setIndustryMediumType(data.getIndustryMediumType());
                addList.add(dbCompanyInfo);
            }else{
                PreMuCompanyInfo preMuCompanyInfo1 = existRecordMap.get(uscc);
                dbCompanyInfo.setUscc(uscc);
                dbCompanyInfo.setId(preMuCompanyInfo1.getId());
                dbCompanyInfo.setCompanyName(data.getCompanyName());
                dbCompanyInfo.setProvince(data.getProvince());
                dbCompanyInfo.setCity(data.getCity());
                dbCompanyInfo.setCounty(data.getCounty());
                dbCompanyInfo.setVillage(data.getVillage());
                dbCompanyInfo.setYear(String.valueOf(dto.getYear()));
                //根据数据表存在的module_type和moduleSign获取最终的moduleType的值
                //String oldModuleType = (String) preMuCompanyInfo1.getModuleType();
                //String moduleTypeNew = incModuleType(moduleType, oldModuleType);
                dbCompanyInfo.setModuleType("10");
                dbCompanyInfo.setDelFlag("0");
                String zone = data.getZone();
                if(StringUtils.isNotBlank(zone)){
                    dbCompanyInfo.setZone(data.getZone());
                }
                dbCompanyInfo.setEvaluateByIndustry(data.getEvaluateByIndustry());
                dbCompanyInfo.setIndustryType(data.getIndustryType());
                dbCompanyInfo.setIndustryMediumType(data.getIndustryMediumType());
                updateList.add(dbCompanyInfo);
            }

            SysUser sysUser = new SysUser();
            if(!userDataMap.containsKey(uscc)){
                sysUser.setUserId(IdUtil.simpleUUID());
                sysUser.setUserName(uscc);
                sysUser.setNickName(dbCompanyInfo.getCompanyName());
//                    sysUser.setPassword(SecurityUtils.encryptPassword(StrUtil.subSuf(uscc,-8)));
                sysUser.setPassword(MD5Utils.encrypt(uscc,StrUtil.subSuf(uscc,-8)));
                sysUser.setStatus("0");
                sysUser.setDelFlag("0");
                sysUser.setProvince(dbCompanyInfo.getProvince());
                sysUser.setCity(dbCompanyInfo.getCity());
                sysUser.setDistrict(dbCompanyInfo.getCounty());
                addUserList.add(sysUser);
            }else{
                SysUser sysUser1 = userDataMap.get(uscc);
                sysUser.setUserName(uscc);
                sysUser.setUserId(sysUser1.getUserId());
                sysUser.setNickName(data.getCompanyName());
                sysUser.setPassword(MD5Utils.encrypt(uscc,StrUtil.subSuf(uscc,-8)));
                sysUser.setStatus("0");
                sysUser.setProvince(data.getProvince());
                sysUser.setCity(data.getCity());
                sysUser.setDistrict(data.getCounty());
                updateUserList.add(sysUser);
            }

            PreMuCompanyInfo existRecord = existRecordMap.get(data.getUscc());
            if (existRecord != null) {
                data.setId(existRecord.getId());
                updateList.add(data);
            }

            validateData(dto, data, errorList);
        }



        return new ProcessCompanyInfoVo(addList, updateList, errorList, addUserList, updateUserList);
    }

    private <T> List<List<T>> splitIntoBatches(List<T> data, int batchSize) {
        List<List<T>> batches = new ArrayList<>();
        for (int i = 0; i < data.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, data.size());
            batches.add(new ArrayList<>(data.subList(i, endIndex)));
        }
        return batches;
    }


    // 批量插入
    private void batchInsert(List<PreMuCompanyInfo> list, String evaluationFlag) {
        if (list.isEmpty()) return;

        int batchSize = 100;
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            if(StringUtils.equals(evaluationFlag,"1")){
                preMuCompanyInfoMapper.batchPreMuCompanyInfoData(list.subList(i, end));
            }else if(StringUtils.equals(evaluationFlag,"2")){
                preMuCompanyInfoNoMapper.batchPreMuCompanyInfoNoData(list.subList(i, end));
            }
        }
    }

    // 批量更新
    private void batchUpdate(List<PreMuCompanyInfo> list, String evaluationFlag) {
        if (list.isEmpty()) return;

        int batchSize = 100;

        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            if(StringUtils.equals(evaluationFlag,"1")){
                preMuCompanyInfoMapper.batchUpdatePreMuCompanyInfoData(list.subList(i, end));
            }else if(StringUtils.equals(evaluationFlag,"2")){
                preMuCompanyInfoNoMapper.batchUpdatePreMuCompanyInfoNoData(list.subList(i, end));
            }
        }


    }


    private void batchInsertUser(List<SysUser> list) {
        if (list.isEmpty()) return;

        int batchSize = 200;
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            sysUserMapper.batchInsertUser(list.subList(i, end));
            batchSaveUserRoleInfo(list.subList(i, end));
        }
    }

    // 批量更新
    private void batchUpdateUser(List<SysUser> list) {
        if (list.isEmpty()) return;

        int batchSize = 200;

        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            sysUserMapper.batchUpdateUser(list.subList(i, end));
        }


    }

    private void  validateData(PreMuCompanyInfoThirdDto dto, PreMuCompanyInfo data, List<String> errorList) {

        String village = data.getVillage();
        if (village != null && village.trim().length() == 12) {
            String county = village.trim().substring(0, 6);
            if (!county.equals(dto.getCounty())) {
                errorList.add( "企业 " + data.getCompanyName() + "不允许添加其他区县数据");
            }

        }else{
            if(!StringUtils.isEmpty(village)){
                String msg = "企业 " + data.getCompanyName() + " 添加失败：";
                errorList.add(msg + "所在街道乡镇只能用区划12位代码");
            }

        }
        if (data.getIndustryType() == null || "".equals(data.getIndustryType())) {
            String msg = "企业 " + data.getCompanyName() + " 添加失败：";
            errorList.add(msg + "所属行业大类不能为空");
        }
        if ("1".equals(data.getCompanyType())&&(data.getIndustryMediumType() == null || "".equals(data.getIndustryMediumType()))) {
            String msg = "企业 " + data.getCompanyName() + " 添加失败：";
            errorList.add(msg + "所属行业中类不能为空");
        }

        if (!data.getIndustryMediumType().substring(0, 2).equals(data.getIndustryType())) {
            String msg = "企业 " + data.getCompanyName() + " 添加失败：";
            errorList.add(msg + "->行业中类不属于行业大类，请检查导入数据！");
        }
        String evaluateByIndustry = data.getEvaluateByIndustry();
        if (StringUtils.isNotBlank(evaluateByIndustry) && !StrUtil.equalsAny(evaluateByIndustry, "1", "0")) {
            String msg = "企业 " + data.getCompanyName() + " 添加失败：";
            errorList.add(msg + "->是否按行业评价只能填是或者否！");
        }else{
            if("0".equals(evaluateByIndustry)){
                data.setEvaluateByIndustry("否");
            }else{
                data.setEvaluateByIndustry("是");
            }
        }


        List<PreMuImportBenefitEvaluationNo> realList = new ArrayList<PreMuImportBenefitEvaluationNo>();

        List<String> usccList = new ArrayList<String>();

        long count = usccList.stream().distinct().count();
        boolean isRepeat = count < usccList.size();
        if (isRepeat) {
            errorList.add("有重复统一社会信用代码，请检查添加数据！");
        }

        ValidationUtil.validate(realList);

    }
}
